package com.lcxw.hxzbapi.controller.attentioncontroller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.controller.membercontroller.MemberRealization;
import com.lcxw.hxzbapi.entity.pojo.Attention;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.AttentionService;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.StringUtil;

/**
 * @author lcwx
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin
@Validated
public class AttentionUserController {

    private Logger logger = LoggerFactory.getLogger(AttentionUserController.class);

    @Resource
    AttentionService attentionService;

    @Resource
    YwpdMemberService ywpdMemberService;

    @Resource
    MemberRealization memberRealization;

    //获取我关注的
    @PostMapping("/attention/get")
    public Response getAttentionUser(@Valid @RequestBody JSONObject requestParams) {
        long userId = Long.parseLong(requestParams.getString("userId"));
        logger.info("{} want to get attention user", userId);

        List<Long> attuIdList = attentionService.getAttentionUserbyUserId(userId);
        List<JSONObject> attInfos = new ArrayList<>();
        try {
            for (Long attUserId : attuIdList) {
                JSONObject attInfo = memberRealization.getUserImgNickName(attUserId);
                if (null != attInfo) {
                    double distance = memberRealization.getDistance(userId, attUserId);
                    attInfo.put("distance", distance);
                    attInfos.add(attInfo);
                }
            }
        } catch (Exception e) {
            return Response.dbFail(logger, "获取用户信息");
        }
        return Response.ok(attInfos);
    }

    /**
     * 添加一个关注的人
     *
     * @param requestParams 请求参数
     * @return response
     */
    @PostMapping("/attention/add")
    public Response addAttentionUser(@Valid @RequestBody JSONObject requestParams) {
        logger.info("{} want to add attention user :{}", requestParams.getString("userId"),
            requestParams.getString("attuId"));
        Response response = new Response();
        if (StringUtil.isEmpty(requestParams.getString("attuId"))) {
            logger.error("attuid is null");
            response.setCode(ErrorCode.PARAM_ERROR);
            response.setDesc("attuId 不能为空");
            return response;
        }

        long userId = Long.parseLong(requestParams.getString("userId"));
        long attuId = Long.parseLong(requestParams.getString("attuId"));
        String attype = "member";
        if (userId == attuId) {
            return Response.error(ErrorCode.INVALID_REQ, "不能关注自己");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = sdf.format(new Date());

        try {
            attentionService.addAttentionUser(userId, attuId, attype, addTime);
            logger.info("{} attention user {} success", userId, attuId);
            response.setCode(0);
            response.setDesc("success");

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("db operate fail");
            response.setCode(ErrorCode.INTERNAL_ERROR);
            response.setDesc("数据库操作失败");
            return response;
        }

        return response;
    }

    //删除一个我关注的
    @PostMapping("/attention/delete")
    public Response deleteAttentionUser(@Valid @RequestBody JSONObject requestParams) {
        logger.info("{} want to delete attention user :{}", requestParams.getString("userId"),
            requestParams.getString("attuId"));

        Response response = new Response();
        if (StringUtil.isEmpty(requestParams.getString("attuId"))) {
            logger.error("attuId is null");
            response.setCode(ErrorCode.PARAM_ERROR);
            response.setDesc("attuId 不能为空");
            return response;
        }

        long userId = Long.parseLong(requestParams.getString("userId"));
        long attuId = Long.parseLong(requestParams.getString("attuId"));
        String attype = "member";

        try {
            attentionService.deleteAttentionUser(userId, attuId, attype);
            response.setCode(0);
            response.setDesc("success");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("db operate fail");
            response.setCode(ErrorCode.INTERNAL_ERROR);
            response.setDesc("数据库操作失败");
            return response;
        }

        return response;

    }

    /**
     * 获取一个用户，查询是否已关注，并返回被查询者的头像/昵称等信息
     */
    @PostMapping("/attention/queryOne")
    public Response queryAtt(@RequestBody JSONObject requestBody) {
        long userId = Long.parseLong(requestBody.getString("userId"));
        long attuId = Long.parseLong(requestBody.getString("attuId"));
        String attype = requestBody.getString("attype");
        JSONObject attInfo;
        try {
            attInfo = memberRealization.getUserImgNickName(attuId);
            attInfo.put("isAttention", memberRealization.isAtt(userId, attuId, attype));
        } catch (Exception e) {
            return Response.dbFail(logger, "获取用户信息");
        }

        return Response.ok(attInfo);
    }

    /**
     * 获取我的粉丝接口
     */
    @PostMapping("/attention/myFans/get")
    public Response getMyFans(@RequestBody JSONObject requestBody) {
        long userId = Long.parseLong(requestBody.getString("userId"));
        List<Long> fansIdList = attentionService.getFans(userId, "member");
        List<JSONObject> fansInfoList = new ArrayList<>();
        try {
            for (Long fansId : fansIdList) {
                JSONObject fansInfo = memberRealization.getUserImgNickName(fansId);
                if (null != fansInfo) {
                    double distance = memberRealization.getDistance(userId, fansId);
                    fansInfo.put("distance", distance);
                    int isAttention = memberRealization.isAtt(userId, fansId, "member");
                    fansInfo.put("isAttention", isAttention);
                    fansInfoList.add(fansInfo);
                }
            }
        } catch (Exception e) {
            return Response.dbFail(logger, "获取用户信息");
        }

        return Response.ok(fansInfoList);
    }

    /**
     * 获取我的好友，即互相关注的用户
     */
    @PostMapping("/attention/friend/getAll")
    public Response getMyFriends(@RequestBody JSONObject requestBody) {
        long userId = Long.parseLong(requestBody.getString("userId"));
        String attype = "member";
        List<Long> fansIdList = attentionService.getFans(userId, attype);
        List<Long> friendsIdList = new ArrayList<>();
        List<JSONObject> friends = new ArrayList<>();
        for (Long fansId : fansIdList) {
            if (1 == memberRealization.isAtt(userId, fansId, attype) && 1 == memberRealization
                .isAtt(fansId, userId, attype)) {
                friendsIdList.add(fansId);
            }
        }
        try {
            for (Long fansId : friendsIdList) {
                JSONObject fansInfo = memberRealization.getUserImgNickName(fansId);
                if (fansInfo != null) {
                    double distance = memberRealization.getDistance(userId, fansId);
                    fansInfo.put("distance", distance);
                    friends.add(fansInfo);
                }
            }
        } catch (Exception e) {
            return Response.dbFail(logger, "获取用户信息");
        }
        return Response.ok(friends);
    }


}
